import React, { useState } from "react";
import "./styleChat.scss";
import axios from "axios";
import doubao from '../../assets/images/豆包.jpg'
import avatar  from  '../../assets/images/头像.jpg'

const Chat = () => {
  const [list, setList] = useState([]);
  const [message, setMessage] = useState("")
  const handleEnter = async (e) => {
    if (e.keyCode === 13) {
      setList((prev) => [...prev, { pos: "right", content: e.target.value }]);
          setMessage(""); // 清空输入框
       try {
         const resp = await axios.get(`http://localhost:3000/doubao?content=${e.target.value}`);
        console.log("API响应原始数据:", resp.data); // 检查此处是否显示正常中文
      setList((prev) => [...prev, { pos: "left", content: resp.data }]);
    } catch (error) {
      console.error("请求错误:", error);
      setList((prev) => [...prev, { pos: "left", content: "请求失败,请检查网络或API" }]);
    }
    }
  };
 
  return (
    <div className="doubao">
      <h1>欢迎使用豆包大模型！！！！</h1>

    <div className="list">
      {list.map((v, i) => {
        return (
          <div className={`message-container ${v.pos}`} key={i}>
            {/* 左边显示豆包头像 */}
            {v.pos === "left" && (
              <img 
                src={doubao}
                alt="豆包" 
                className="avatar left"
              />
            )}

            <div className={`bubble ${v.pos}`}>
             
                {v.content}
             
            </div>

            {/* 右边显示用户头像 */}
            {v.pos === "right" && (
              <img 
                src={avatar}
                alt="用户" 
                className="avatar right"
              />
            )}
          </div>
        );
      })}
    </div>

      <div className="bottom">
        <input
          placeholder="请输入问题..."
          onKeyDown={(e) => handleEnter(e)}
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        ></input>
      </div>
    </div>
  );
};

export default Chat;
